#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;

struct ListNode {
    int val;
    ListNode* next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode* next) : val(x), next(next) {}
    
};

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* head = new ListNode(-1);
        ListNode* tail = head;
        int carry = 0;
        while (l1 || l2 || carry)
        {
            int sum = 0;
            if (l1)
            {
                sum += l1->val;
                l1 = l1->next;
            }
            if (l2)
            {
                sum += l2->val;
                l2 = l2->next;
            }
            sum += carry;
            tail->next = new ListNode(sum % 10);
            tail = tail->next;
            carry = sum / 10;
        }
        if (carry) tail->next = new ListNode(carry);
        return head->next;
    }

    ListNode* swapPairs(ListNode* head) {
        if (head == nullptr) return nullptr;
        if (!head->next) return head;
        ListNode* dummy = new ListNode(-1);
        ListNode* prev = dummy, * cur = head, * next = head->next, * nnext = head->next->next;
        while (cur && next)
        {
            prev->next = next;
            cur->next = nnext;
            next->next = cur;
            prev = cur;
            cur = nnext;
            if (cur) next = cur->next;
            if (next) nnext = next->next;
        }
        return dummy->next;
    }

    ListNode* reverse(ListNode* head)
    {
        if (!head || !head->next) return head;
        ListNode* l1 = nullptr, * l2 = head, * l3 = l2->next;
        while (l2)
        {
            l2->next = l1;
            l1 = l2;
            l2 = l3;
            if (l3)l3 = l3->next;
        }
        return l1;
    }
    void reorderList(ListNode* head) {
        ListNode* dummy = new ListNode(-1, head);
        ListNode* slow = dummy, * fast = dummy;
        while (fast && fast->next)
        {
            slow = slow->next;
            fast = fast->next->next;
        }
        ListNode* p = slow->next;
        slow->next = nullptr;
        ListNode* reList = reverse(p);
        ListNode* cur = head;
        ListNode* newhead = new ListNode(-1);
        ListNode* tail = newhead;
        while (cur)
        {
            tail->next = cur;
            cur = cur->next;
            tail = tail->next;

            if (reList)
            {
                tail->next = reList;
                reList = reList->next;
                tail = tail->next;
            }
        }
        head = newhead->next;
    }
};